package cn.yuan.pet.service.impl;

import cn.yuan.basic.service.impl.BaseServiceImpl;
import cn.yuan.pet.domain.Pet;
import cn.yuan.pet.domain.PetDetail;
import cn.yuan.pet.mapper.PetDetailMapper;
import cn.yuan.pet.mapper.PetMapper;
import cn.yuan.pet.service.IPetService;
import cn.yuan.user.domain.User;
import cn.yuan.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService{

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void remove(Long petId) {
        //1.通过服务Id 删除服务详情
        petDetailMapper.removeByPetId(petId);
        petMapper.remove(petId);
    }

    @Override
    public void save(Pet pet) {
        petMapper.save(pet);//需要返回主键
        PetDetail detail = pet.getDetail();
        if(detail != null){
            detail.setPet_id(pet.getId());
            petDetailMapper.save(detail);
        }
    }

    @Override
    public void update(Pet pet) {
        petMapper.update(pet);
        PetDetail detail = pet.getDetail();
        if(detail != null){
            detail.setPet_id(pet.getId());
            if(detail.getId() != null){
                petDetailMapper.update(detail);
            }else{
                petDetailMapper.save(detail);
            }

        }

    }

    @Override
    public PetDetail findDetailByPetId(Long petId) {
        return petDetailMapper.loadByPetId(petId);
    }



    /**
     * 批量上架或下架
     * @param ids
     * @param flag   0下架  1 上架
     */
    @Override
    public void onOrOffSale(List<Long> ids, int flag) {
        Map<String,Object> map = new HashMap<>();
        map.put("ids", ids);
        if(flag==1){
            map.put("onsaletimg", new Date());
            petMapper.onsale(map);
        }else {
            map.put("offsaletime", new Date());
            petMapper.offSale(map);
        }
    }

    @Override
    public Pet loadByIdDetail(Long id) {
        return petMapper.loadByIdDetail(id);
    }

    @Override
    @Transactional
    public void adopt(Long id, Long loginInfoId) {
        // 1.修改宠物状态下架 下架时间
        Pet pet = petMapper.loadById(id);
        if(pet!=null){
            pet.setState(0);
            pet.setOffsaletime(new Date());
            User user = userMapper.loadByLoginInfoId(loginInfoId);
            pet.setUser_id(user.getId());
            petMapper.update(pet);
            //3.@TODO 生成订单并支付
        }
    }
}
